import time

import json_repair, json
import re
import threading
import datetime
from bid.generate.tools.teamFilter import team_filter
from bid.generate.tools.projectFilter import projectFilter, dawate_streaming
from bid.generate.models import ExBid

#提取标的和标包信息
def get_target_bid(text):
    #按标的切分
    biaodi_ls = text.split('标的')
    biaodi_ls = [i.replace("【",'[').replace("】",']') for i in biaodi_ls if i.strip()]

    result = []

    #获取数字的
    pattern_num = r'\d+'

    for biaodi in biaodi_ls:
        # 获取标的数字
        biaodi_id = re.findall(pattern_num, biaodi)[0]

        if '标包' in biaodi:
            #找出标包位置
            pattern = r"\[(.*?)\]"
            biaobao_str = re.findall(pattern, biaodi, re.DOTALL)[0]
            #按标包切分
            biaobao_ls = biaobao_str.split('标包')
            biaobao_ls = [i for i in biaobao_ls if i.strip()]
            for biaobao in biaobao_ls:
                # 获取标的数字
                matches = re.findall(pattern_num, biaobao)
                result.append(f"标的{biaodi_id}-标包{matches[0]}")
        else:
            #获取标的数字
            result.append(f"标的{biaodi_id}")

    return result

#需要先执行团队管理生成，再执行负责人业绩生成
def team_pm_project(team_rule, pm_project_rule, bid_id, company, dept,config_params):
    # 生成团队
    header_id = team_filter(team_rule, bid_id, company, dept,config_params)

    #生成负责人业绩
    projectFilter(pm_project_rule, bid_id, company, config_params, int(header_id))

#生成公司业绩、负责人业绩和团队管理
def ai_generate_project_team(bid_id, config_params):
    #获取招标文件内容
    bid = ExBid.objects.filter(id=bid_id).select_related('bidParse', 'createBy__company', 'createBy__company', 'package').first()

    #公司id
    company = bid.createBy.company.id
    dept = bid.createBy.dept.name

    #获取解析内容
    # data = json.loads(bid.bidParse.text)
    #
    # #获取该标包对应的标的和标包，按标的1-标包1组合
    # target_bid = get_target_bid(f"{bid.targetName}[{bid.bidPackage}]")[0]
    #
    # #获取专用资格要求
    # if '专用资格要求' in data.keys():
    #     special_qua = ''
    #     special_qua_ls = data['专用资格要求']
    #
    #     #使用标包进行匹配
    #     for value in special_qua_ls:
    #         target_bid_ls = get_target_bid(value['关联标的/标包/标段'])
    #         if target_bid in target_bid_ls:
    #             for key in value.keys():
    #                 if '要求' in key:
    #                     special_qua = value[key]
    #             break
    #
    #     #如果没有匹配到，使用标的进行匹配
    #     if not special_qua:
    #         target = target_bid.split('-')[0]
    #         for value in special_qua_ls:
    #             target_bid_ls = get_target_bid(value['关联标的/标包/标段'])
    #             if target in target_bid_ls:
    #                 for key in value.keys():
    #                     if '要求' in key:
    #                         special_qua = value[key]
    #                 break
    #
    # else:
    #     special_qua = '无'
    #
    # #获取评分标准
    # project_std = ''
    # pm_project_std = ''
    # pm_std = ''
    # team_std = ''
    # for key, value in data['详细评审标准'].items():
    #     if target_bid in value['适用标包列表']:
    #         for sub_key, sub_value in value.items():
    #             if '商务评审' in sub_key:
    #                 for i in sub_value:
    #                     if i['详细评审项'] == '业绩':
    #                         project_std = i['详细评审分项要素']
    #                     elif i['详细评审项'] == '项目负责人业绩':
    #                         pm_project_std = i['详细评审分项要素']
    #                     elif i['详细评审项'] == '项目负责人素质':
    #                         pm_std = i['详细评审分项要素']
    #             elif '技术评审' in sub_key:
    #                 for i in sub_value:
    #                     if '团队' in i['详细评审项']:
    #                         team_std = i['详细评审分项要素']
    #
    #         break

    #获取标包对应的要求
    package = bid.package

    #获取专业资格要求
    if package.special:
        special_qua = package.special
    else:
        special_qua = '无'

    #获取项目负责人要求
    project_std = ''
    pm_project_std = ''
    # pm_std = ''
    team_std = ''

    #获取详细评审标准
    # detail_review = package.review
    # detail_review = json_repair.loads(detail_review)

    # with open('详细评审标准1.json', 'w') as f:
    #     json.dump(detail_review,f, ensure_ascii=False)

    # for key, value in detail_review.items():
    #     for item in value:
    #         #筛选有详细评审项的
    #         if '详细评审项' not in item.keys():
    #             continue
    #
    #         #优先负责人业绩
    #         if '负责人' in item['详细评审项'] and '业绩' in item['详细评审项']:
    #             pm_project_std = item['详细评审分项要素']
    #         elif '业绩' in item['详细评审项']:
    #             project_std = item['详细评审分项要素']
    #         elif '负责人' in item['详细评审项'] and '素质' in item['详细评审项']:
    #             # pm_std = item['详细评审分项要素']
    #             team_std += f"{item['详细评审分项要素']}\n"
    #         elif '负责人' in item['详细评审项'] and '资质' in item['详细评审项']:
    #             # pm_std = item['详细评审分项要素']
    #             team_std += f"{item['详细评审分项要素']}\n"
    #         elif '团队' in item['详细评审项']:
    #             # team_std = item['详细评审分项要素']
    #             team_std += f"{item['详细评审分项要素']}\n"

    print('专用资格要求: ',[special_qua])
    print('公司业绩: ',[project_std])
    print('负责人业绩: ',[pm_project_std])
    print('团队管理: ',[team_std])

    # import time
    # time.sleep(11000)

    #有招标文件id是，需要大模型抽取规则，否则直接获取
    if bid.bid_parse:

        prompt = '''
        根据传入的文本，提取出项目负责人业绩（项目）要求、项目负责人素质要求、业绩（项目）要求和团队要求，输出格式如下，如果没有，为空即可
        json的键必须为：项目负责人业绩要求、项目负责人素质要求、业绩要求、团队要求
        
        ###注意###
        1、项目负责人业绩要求必须明确是项目负责人的业绩要求才可以
        2、项目负责人业绩要求可能在团队要求中
        3、团队要求不包含负责人的业绩和素质要求
        4、如果有正偏差、无偏差、负偏差的要求时也需要添加到对应的要求中
        
        ```json
        {
            "项目负责人业绩要求": "要求",
            "项目负责人素质要求"： "要求",
            "业绩要求": "要求",
            "团队要求": "要求",
        }
        ```
        '''
        query = f"{prompt}传入文本：\n{package.review}"

        # with open('测试.txt', 'w') as f:
        #     f.writelines(query)

        # import time
        # time.sleep(11000)

        #调用大模型
        answer = dawate_streaming(query, config_params)

        # 获取返回的json
        pattern = r"```json(.*?)```"
        matches = re.findall(pattern, answer, re.DOTALL)
        llm_data = json_repair.loads(matches[-1])

        # pm_project_std = llm_data['项目负责人业绩要求']
        # team_std = f"{llm_data['项目负责人素质要求']}\n{llm_data['其他要求']}"
        project_std = llm_data['业绩要求']
        pm_project_std = llm_data['项目负责人业绩要求']
        team_std = f"{llm_data['项目负责人素质要求']}\n{llm_data['团队要求']}"
    else:
        if package.review:
            review = json.loads(package.review)
            #获取各个规则
            project_std = review['project_rule'] if 'project_rule' in review.keys() else ''
            pm_project_std = review['pm_project_rule'] if 'pm_project_rule' in review.keys() else ''
            team_std = review['team_rule'] if 'team_rule' in review.keys() else ''

    print('========================')
    print('专用资格要求: ',[special_qua])
    print('公司业绩: ',[project_std])
    print('负责人业绩: ',[pm_project_std])
    print('团队管理: ',[team_std])

    # import time
    # time.sleep(11000)

    #初始化线程池
    threadpool = []
    today_year = datetime.datetime.now().year

    #如果团队规则为空，则不需要推荐团队和业绩
    if not team_std.strip():
        #获取团队规则
        team_rule = f"项目名称：{package.name}\n评审标准：{team_std}"

        # 获取负责人业绩规则
        pm_project_rule = f"今年年份：{today_year}\n标的名称：{bid.target.name}\n标包名称：{package.name}\n专用资格要求：{special_qua}\n评审标准：{pm_project_std}"

        threadpool.append(threading.Thread(target=team_pm_project, args=(team_rule,pm_project_rule,bid_id,company,dept,config_params)))

    #获取公司业绩规则
    project_rule = f"今年年份：{today_year}\n标的名称：{bid.target.name}\n标包名称：{package.name}\n专用资格要求：{special_qua}\n评审标准：{project_std}"
    #生成公司业绩
    threadpool.append(threading.Thread(target=projectFilter, args=(project_rule, bid_id,company,config_params)))
    # projectFilter(project_rule, bid_id)

    # 启用和阻塞线程
    for th in threadpool:
        th.start()
    for th in threadpool:
        threading.Thread.join(th)

    #完成后更新数据库状态
    ExBid.objects.filter(id=bid_id).update(status='done')

    print('生成完成')

    # projectFilter(project_rule, bid_id, int(header_id))

    # print(team_rule)

# ai_generate_project_team(8)